package dotdashdot.bradz.trendsettr;

//import com.coboltforge.slidemenuexample.R;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

import android.app.ListActivity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
//import android.support.v4.app.ActionBarDrawerToggle;
//import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.androidplot.xy.SimpleXYSeries;
import com.androidplot.xy.XYPlot;
import com.androidplot.xy.XYSeries;


public class ActivitySeeTrend extends ListActivity {
    /*private String[] TrendingTopics;
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
    private CharSequence title;
    private ClassTrendingContainer container;*/
    
    private ListView list_view;
    private ClassTrendsettrAdapter adapter;
    private ClassTrendingContainer trend_container;
    private Context self;
    private ClassFonts fonts;
    //private Bundle extras;
    private ClassNetworkHelper helper;
    private ArrayList<HashMap<String, String>> aList;
    private ClassGraphInfo info;
    private ClassFilterPopup info_popup;
    private ClassUserCredentials credentials;
    private ApplicationGlobalVars globals;
    
    Handler myHandler = new Handler() {

  	    @Override
  	    public void handleMessage(Message msg) {
  	        switch (msg.what) {
  	        case 0:
  	        	init_see_trend_list();
  	            break;
  	        case 1:
  	        	create_trend_graph();
	            break;
  	        case 2:
  	        	refresh_trend_list();
  	        	break;
  	        case 5:
  	        	format_credentials();
  	        	break;
  	        default:
  	            break;
  	        }
  	    }
  	};
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
        setContentView(R.layout.activity_see_trend);
        //extras = getIntent().getExtras();
        fonts = new ClassFonts(this.getAssets());
        trend_container = new ClassTrendingContainer();
        helper = new ClassNetworkHelper(this,((ApplicationGlobalVars) this.getApplication()));
        self = this;
        
        globals = ((ApplicationGlobalVars) this.getApplication());
		
		credentials = new ClassUserCredentials(globals);
		
        list_view = getListView();
        list_view.setTextFilterEnabled(true);
        
        set_loading_item();
        
		if(!credentials.logged_in){
			helper.apply_for_credentials(credentials, myHandler);
		}else{
			format_credentials();
		}
        //list_view.addHeaderView(getLayoutInflater().inflate(R.layout.activity_see_trend_header, null, false),null,false);
        //list_view.setHeaderDividersEnabled(true);
        
        //set_loading_item();
        
        trend_container.print_info();
        format_nav_tab();
        //set_list_header_formats();
        //set_list_formats();
    }
    
    @Override
    public void onResume(){
    	super.onResume();
    	//trend_container = new ClassTrendingContainer();
    	//helper.get_all_from_network_see_trend(trend_container, myHandler);
    	if(!credentials.logged_in && !helper.applying()){
			helper.apply_for_credentials(credentials, myHandler);
		}else{
			format_credentials();
		}
    }
    
    private void refresh_trend_list(){
    	aList = new ArrayList<HashMap<String,String>>();
    	HashMap<String, String> map;
    	for(ClassTopic topic:trend_container.get_topic_list()){
    		if(info_popup.get_checked_filters().contains(topic.get_name())){
	        	for(ClassTrend trend:topic.get_trend()){
	        		int total = trend.get_info().total;
	        		int ups = trend.get_info().ups;
	        		Log.i("ActivitySeeTrend","Total: " + total);
	        		Log.i("ActivitySeeTrend","Ups: " + ups);
	        		int percent = (int)(((float) ups / (float) total) * 100);
	        		Timestamp created = trend.get_info().date_created;
	        		Log.i("ActivitySeeTrend","Voted: " + total);
	        		Log.i("ActivitySeeTrend","Ups: " + percent);
	        		map = new HashMap<String, String>();
			        map.put("Trend", trend.get_name());
			        map.put("Topic", "" + topic.get_name());
			        map.put("Votes", "" + total);
			        map.put("Ups", "" + percent);     
			        map.put("Date Created", new SimpleDateFormat("MM.dd.yy").format(created));
			        map.put("Voted", "" + trend.get_info().vote);
			        aList.add(map);
	        	}
    		}
        }
    	adapter = new ClassTrendsettrAdapter(this, aList, R.layout.activity_see_trend_row, 
        		new String[]{"Trend","Votes","Ups","Date Created"}, new int[]{R.id.see_trend_trend,R.id.see_trend_votes,
        		R.id.see_trend_ups,R.id.see_trend_date_create},fonts, info_popup);
    	list_view.setAdapter(adapter);
    	adapter.filter_opinions(info_popup.get_filter_opinions());
    	adapter.notifyDataSetChanged();
    }
    
    private void set_loading_item(){
    	aList = new ArrayList<HashMap<String,String>>();
        HashMap<String, String> map;

		map = new HashMap<String, String>();
        map.put("Trend", "Loading...");
        map.put("Topic", "Loading...");
        map.put("Votes", "0");
        map.put("Ups", "0");     
        map.put("Date Created", new SimpleDateFormat("MM.dd.yy").format(new Timestamp((new java.util.Date()).getTime())));
        map.put("Voted", "-1");
        aList.add(map);

        adapter = new ClassTrendsettrAdapter(this, aList, R.layout.activity_see_trend_row, 
        		new String[]{"Trend","Votes","Ups","Date Created"}, new int[]{R.id.see_trend_trend,R.id.see_trend_votes,
        		R.id.see_trend_ups,R.id.see_trend_date_create},fonts, info_popup);
        
        list_view.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }
    
    private void init_see_trend_list(){
    	
    	aList = new ArrayList<HashMap<String,String>>();
        HashMap<String, String> map;
    	ArrayList<String> topic_list = new ArrayList<String>();
    	
        for(ClassTopic topic:trend_container.get_topic_list()){
        	topic_list.add(topic.get_name());
        	for(ClassTrend trend:topic.get_trend()){
        		int total = trend.get_info().total;
        		//You can't plot a line with less than two points...
        		if(total>1){
	        		int ups = trend.get_info().ups;
	        		Log.i("ActivitySeeTrend","Total: " + total);
	        		Log.i("ActivitySeeTrend","Ups: " + ups);
	        		int percent = (int)(((float) ups / (float) total) * 100);
	        		Timestamp created = trend.get_info().date_created;
	        		Log.i("ActivitySeeTrend","Voted: " + total);
	        		Log.i("ActivitySeeTrend","Ups: " + percent);
	        		map = new HashMap<String, String>();
			        map.put("Trend", trend.get_name());
			        map.put("Topic", "" + topic.get_name());
			        map.put("Votes", "" + total);
			        map.put("Ups", "" + percent);     
			        map.put("Date Created", new SimpleDateFormat("MM.dd.yy").format(created));
			        map.put("Voted", "" + trend.get_info().vote);
			        map.put("Meta", "" + trend.get_link());
			        aList.add(map);
        		}
        	}
        }

        adapter = new ClassTrendsettrAdapter(this, aList, R.layout.activity_see_trend_row, 
        		new String[]{"Trend","Votes","Ups","Date Created"}, new int[]{R.id.see_trend_trend,R.id.see_trend_votes,
        		R.id.see_trend_ups,R.id.see_trend_date_create},fonts, info_popup);
        
        /*adapter = new ClassTrendsettrAdapter(this, aList, R.layout.activity_see_trend_row, 
        		new String[]{"Trend","Votes","Ups","Date Created"}, new int[]{R.id.see_trend_trend,R.id.see_trend_votes,
        		R.id.see_trend_ups,R.id.see_trend_date_create},fonts);*/
        
        load_filter_popup_task pop_load = new load_filter_popup_task();
        pop_load.list_view = list_view;
        pop_load.execute();
        
        //list_view.setAdapter(adapter);
        
        /*
         * int firstPosition = listView.getFirstVisiblePosition() - listView.getHeaderViewsCount();
         */
        //list_view.setAdapter(adapter);
        
        /*Log.i("ActivitySeeTrend","List count: " + list_view.getCount());
        for(int i = 0; i < list_view.getCount();i++){
        	Log.i("ActivitySeeTrend","List position: " + i);
        	set_list_formats(list_view.getAdapter().getView(i, null, null));
        }*/
        
        // Creating an item click listener, to open/close our toolbar for each item
        list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
            	
            	Log.i("ActivitySeeTrend","Position: " +  position);
            	adapter.set_click(position);
            	//First we need to close all the parent views...
            	for(int i = 0; i < parent.getChildCount();i++){
            		View v = parent.getChildAt(i);
            		View details = v.findViewById(R.id.toolbar);
            		
            		Log.i("ActivitySeeTrend","i: " +  i);
            		Log.i("ActivitySeeTrend","visibility: " +  details.getVisibility());
            		
            		if(details != null && details.getVisibility() == View.VISIBLE && i != position && i != adapter.get_click()){
            			Log.i("ActivitySeeTrend","Closing: " +  i);
            			ClassExpandAnimation expandAni = new ClassExpandAnimation(details, 500);
            			details.startAnimation(expandAni);
            		//We don't need to worry if this view is visible or not. If it is it expands, if it isn't the adapter will close it...
            		}
            	}
            	
            	info = new ClassGraphInfo(new ArrayList<ClassGraphData>(), aList.get(position).get("Meta"), aList.get(position).get("Trend"),view);

            	//Log.i("SeeTrend", "ListInfo - position: " + info.position);
            	//Log.i("SeeTrend", "ListInfo - trend: " + info.trend);
            	
            	//If something is being collapsed, we dont need to query for the history...
            	if(adapter.get_click()!=-1){
            		helper.get_all_from_network_trend_history(info, myHandler);
            	}else{
            		Log.i("ActivitySeeTrend","Closing Current View");
            		//This is for collapsing the current view if it is clicked twice
            		View expandable = view.findViewById(R.id.toolbar);
            		ClassExpandAnimation expandAni = new ClassExpandAnimation(expandable, 500);
                    expandable.startAnimation(expandAni);
            	}
            	
            	//adapter.notifyDataSetChanged();
            }
        });
        
        //self = this;
    }
    
    private void create_trend_graph(){
    	//Then open up the clicked view...
    	
    	Log.i("SeeTrend", "ListInfo - create_trend_graph - return");
    	//Log.i("SeeTrend", "ListInfo - position: " + info.position);
    	Log.i("SeeTrend", "ListInfo - trend: " + info.trend);
    	
        /*Number[] test_number = info.get_vote_array();
        for(Number number:test_number){
        	Log.i("create_trend_graph","Point: " + number.toString());
        }*/
        
    	//This needs to be passed to the adapter bc the listview sucks ass and recycles things
        Log.i("SeeTrend", "Reseting new layout");
        
        //SimpleXYSeries series = new SimpleXYSeries(Arrays.asList(info.get_vote_array()), SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "");
        
        XYSeries series2 = new SimpleXYSeries(
                Arrays.asList(info.get_date_array()),
                Arrays.asList(info.get_vote_array()),
                "");

        //Just error checking. This should always be true.
        if(series2.size()>0){
        	//Can't be passing empty arrays to this bitch
            /*adapter.set_graph_info(new SimpleXYSeries(Arrays.asList(info.get_vote_array()), SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, ""),
            		aList.get(info.position).get("Trend"), this);*/
        	adapter.set_graph_info(series2,info.trend, info.meta, getResources().getColor(R.color.navigation_color));
            adapter.notifyDataSetChanged();
        }
    }
    
    private void format_credentials(){
    	TextView user_name_text_view = (TextView) this.findViewById(R.id.user_name_footer);
    	TextView user_rank_text_view = (TextView) this.findViewById(R.id.user_rank_footer);
    	user_name_text_view.setTypeface(fonts.get_font("medium_italic"));
    	user_rank_text_view.setTypeface(fonts.get_font("medium"));
    	user_name_text_view.setText(credentials.name);
    	user_rank_text_view.setText("Trendsettr Rank: "+credentials.rank);
    	globals.set_credentials_store(credentials);
    	helper.get_all_from_network_see_trend(trend_container, myHandler);
    }
    
	private void format_nav_tab(){
		/*final TextView title_text = (TextView) findViewById(R.id.top_title_text);
		title_text.setTypeface(fonts.get_font("italic"));*/
		
		final Button navigation_text = (Button) findViewById(R.id.top_navigation_button);
		navigation_text.setTypeface(fonts.get_font("cond_medium"));
		
        //FrameLayout frame = (FrameLayout) findViewById(R.id.see_trend_row);
        //frame.setAlpha(0);
	}
    
    //Make sure that the network is active and working...
  	private class load_filter_popup_task extends AsyncTask<Void, Void, Void> {
  		ArrayList<String> topic_list;
  		ListView list_view;

  		@Override
        protected void onPreExecute() {
  			topic_list = new ArrayList<String>();
  			
  			/*
  			 * Popularity
  			 * Alphabetical
  			 * Date Created
  			 * Trend Length
  			 */
  			
  			topic_list.add("Alphabetical");
  			topic_list.add("Popularity");
  			topic_list.add("Date Created");
  			topic_list.add("Trend Length");
  			
  	        /*for(ClassTopic topic:trend_container.get_topic_list()){
  	        	topic_list.add(topic.get_name());
  	        }*/
  		}
  		
  		@Override
  		protected Void doInBackground(Void... arg0) {
  			info_popup = new ClassFilterPopup(self,fonts,topic_list,list_view,self,list_view, myHandler,false);
  			return null;
  		}
  		
  		@Override
  	    protected void onPostExecute(Void v) {
  			//View top_bar = (View) findViewById(R.id.top_bar_layout);
  			info_popup.attach_popup_window((View)findViewById(R.id.top_navigation_button),getWindowManager().getDefaultDisplay());
  			
  			list_view.setAdapter(adapter);
  		}
  		
  	}
} 